<template>
    <div class="container common-container">
        <el-header class="other_header" style="height: 40px; line-height: 40px; text-align: center; color: #5d9cec">创建题目</el-header>
        <el-form ref="form" :model="form" label-width="80px" :rules="rules">
            <el-form-item label="题目类型" prop="type">
                <!-- 添加选项 -->
                <el-radio-group v-model="form.type" size="medium" @change="radioChange">
                    <el-radio-button label="radio">单选</el-radio-button>
                    <el-radio-button label="checkbox">多选</el-radio-button>
                    <el-radio-button label="input">单项填空</el-radio-button>
                    <el-radio-button label="select">选择填空</el-radio-button>
                </el-radio-group>
            </el-form-item>

            <!--     <el-form-item>
                <el-button type="primary" @click="onSubmit">保存</el-button>
                <el-button type="primary" @click="onPreview">预览</el-button>
            </el-form-item> -->

            <el-form-item label="搜索题目">
                <el-row>
                    <el-col :span="6">
                        <el-select v-model="value" placeholder="请选择" @change="selectOption">
                            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value"> </el-option>
                        </el-select>
                    </el-col>
                    <el-col :span="8">
                        <el-input placeholder="请输入题目标题或题目描述" prefix-icon="el-icon-search" v-model="keyword" />
                    </el-col>
                </el-row>
            </el-form-item>

            <!-- 遍历已创建的选项渲染 -->
            <Topic :topicList="topicItemList" :typeMap="typeMap" @editData="handleEdit" />

            <!-- 添加选项弹出框 -->
            <div class="additem">
                <el-dialog :title="typeMap[questItem.type]" :visible.sync="showItem" width="50%">
                    <el-form-item label="题目ID号">
                        <el-input v-model="itemId" placeholder="请输入"></el-input>
                    </el-form-item>
                    <el-form-item label="题目标题">
                        <el-input v-model="itemTitle" placeholder="请输入"></el-input>
                    </el-form-item>
                    <el-form-item label="题目描述">
                        <el-input type="textarea" :rows="3" placeholder="请输入" v-model="remark"></el-input>
                    </el-form-item>
                    <el-form-item label="配置选项" v-show="questItem.type != 'input'">
                        <el-input-number v-model="num" @change="handleChange" :min="1" :max="10"></el-input-number>
                    </el-form-item>
                    <div class="dialog">
                        <el-form-item v-for="(text, i) in itemText" :label="`选项${i + 1}`" :key="i" v-show="questItem.type != 'input'">
                            <el-input v-model="itemText[i]" placeholder="请输入"></el-input>
                        </el-form-item>
                    </div>

                    <span slot="footer" class="dialog-footer">
                        <el-button size="medium" @click="clearItem">取 消</el-button>
                        <el-button size="medium" type="primary" @click="determine">确 定</el-button>
                    </span>
                </el-dialog>
            </div>
        </el-form>

        <el-row class="footer" :gutter="20" type="flex" justify="end">
            <el-col :span="2">
                <el-button type="primary" size="medium" @click="onSubmit">保存</el-button>
            </el-col>
            <el-col :span="2">
                <el-button type="primary" size="medium" @click="onPreview">预览</el-button>
            </el-col>
        </el-row>
    </div>
</template>
<script>
import Topic from '../components/Topic';
export default {
    name:'Home',
    components: { Topic },
    data() {
        return {
            value: '',
            matrixsNum: 1,
            num: 1,
            form: {
                itemList: [],
                type: ''
            },
            topicItemList: [],
            itemTitle: '',
            itemId: '',
            remark: '',
            itemText: new Array(1),
            questItem: {},
            showItem: false,
            typeMap: {
                radio: '单选',
                checkbox: '多选',
                input: '问答',
                select: '选择'
            },
            keyword: '',
            options: [
                {
                    value: undefined,
                    label: '全部'
                },
                {
                    value: 'radio',
                    label: '单选'
                },
                {
                    value: 'checkbox',
                    label: '多选'
                },
                {
                    value: 'input',
                    label: '问答'
                },
                {
                    value: 'select',
                    label: '选择'
                }
            ],
            editIndex: '',
            rules: {
                type: [{ required: true, message: '请选择题目类型', trigger: 'change' }],
            }
        };
    },
    watch: {
        showItem() {
            if (!this.showItem) {
                this.clearItem();
            }
        },
        keyword(val) {
            this.filterList();
        }
    },
    methods: {
        add(type) {
            this.questItem.type = type;
            this.showItem = true;
        },

        handleChange(val) {
            this.itemText.length = val;
        },

        async determine() {
            let { questItem, itemText,itemTitle,itemId,remark } = this;
            if (!itemTitle || !itemId || !remark ) {
                this.$message.error('保存失败，您还有信息未填，请检查！');
                return;
            }
            this.keyword = '';
            this.value = '';
            switch (questItem.type) {
                case 'input':
                    await this.handleData();
                    this.clearItem();
                    break;
                case 'radio':
                case 'checkbox':
                case 'select':
                    // 单选、多选、多填
                    for (var i = 0; i < itemText.length; i++) {
                        if (itemText[i] == '' || itemText[i] == undefined) {
                            this.$message.error('保存失败，您还有信息未填，请检查！');
                            return;
                        }
                    }
                    let filterSomeData = this.isRepeat(itemText)
                    if(filterSomeData.length !== itemText.length){
                        this.$message.error('保存失败，选项不能重复，请检查！');
                        return;
                    }
                    await this.handleData();
                    this.clearItem();
                    break;
            }
        },
         isRepeat(arr){
            let newArr = [...new Set(arr)]; //利用了Set结构不能接收重复数据的特点
            return newArr
        },
        handleData() {
            const { editIndex, itemTitle, itemId, remark, itemText, questItem, form } = this;
            this.questItem.title = itemTitle;
            this.questItem.itemId = itemId;
            this.questItem.remark = remark;
            this.questItem.textList = itemText;
            this.topicItemList = form.itemList;
            if (editIndex !== '') {
                this.form.itemList.splice(editIndex, 1, questItem);
                this.topicItemList = form.itemList;
                this.editIndex = '';
            } else {
                this.form.itemList.push(questItem);
            }
        },
        // 关闭弹窗，清空数据
        clearItem() {
            this.num = 1;
            this.itemTitle = '';
            this.itemId = '';
            this.remark = '';
            this.itemText = [''];
            this.questItem = {};
            this.showItem = false;
        },
        //选择过滤
        selectOption() {
            this.filterList();
        },
        filterList(e) {
            const { itemList } = this.form;
            const { value ,keyword } = this;
            let data = []
           
            if(value&&keyword){
                data =  itemList.filter((item) => item['type'].indexOf(value) != -1&&(item['remark'].indexOf(keyword) != -1 || item['title'].indexOf(keyword) != -1));
            }else if(value){
                data =   itemList.filter((item) => item['type'].indexOf(value) != -1);
            }else if(keyword){
                data = itemList.filter((item) => item['remark'].indexOf(keyword) != -1 || item['title'].indexOf(keyword) != -1);
            }else{
                data = itemList
            }
            this.topicItemList = data;
        },
        // 提交
        onSubmit() {
            this.$refs['form'].validate((valid) => {
                if (valid) {
                    if (this.form.itemList.length === 0) {
                        this.$message.error('至少添加一个选项');
                        return;
                    }
                    console.log(this.form);
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        handleEdit(e) {
            console.log('edit==>', e);
            const { item, editIndex } = e;
            /*

            this.itemId = item.itemId;
            this.remark = item.remark;
            this.itemText = item.textList;
            this.questItem = {};
             */

            this.editIndex = editIndex;
            if (item.type !== 'input') {
                this.num = item.textList.length;
                this.showItem = true;
                this.itemId = item.itemId;
                this.remark = item.remark;
                this.questItem = item;
                this.itemTitle = item.title;
                this.itemText = [];
                this.itemText.push(...item.textList);
            } else {
                this.showItem = true;
                this.questItem = item;
                this.itemTitle = item.title;
                this.itemId = item.itemId;
                this.remark = item.remark;
            }
        },
        // 预览
        onPreview() {
            const { topicItemList = [] } = this;
            if (topicItemList.length === 0) {
                this.$message.error('至少添加一个题目');
                return;
            }
            this.$router.push({
                path: `/preview`,
                query: { itemList: topicItemList }
            });
        },
        radioChange(e) {
            this.add(e);
        }
    }
};
</script>
<style scoped>
.container {
    width: 1000px;
    margin: 100px auto;
}

.dialog {
    height: 30vh;
    overflow: auto;
}
.additem {
    padding: 0 30px;
}


</style>